#import "QBPMClient.h"
#import "WorkitemEntry.h"
#import "AcceptResult.h"
#import "Base64.h"
#import "QuestetraBPMAppDelegate.h"
#import "JSON.h"

@implementation QBPMClient

@synthesize contextRoot;

- (id) init {
	self = [super init];
	if(self != nil) {
		authorized = NO;
	}
	return self;
}

- (BOOL) loadConfiguration {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	email = [defaults objectForKey:@"email"];
	password = [defaults objectForKey:@"password"];
	contextRoot = [defaults objectForKey:@"server"];
	// NSLog(@"email:%@ password:%@ contextRoot:%@", email, password, contextRoot);
	if(email == nil || password == nil || contextRoot == nil || [email length] == 0 || [password length] == 0 || [contextRoot length] == 0) {
		return NO;
	}
	return YES;
}

- (NSMutableArray*) fetchWorkitems {
	return [self fetchWorkitemsFromUrl: @"API/PE/Workitem/listAllocated"];
}
- (NSMutableArray*) fetchOfferedTasks {
	return [self fetchWorkitemsFromUrl: @"API/PE/Workitem/listOffered"];
}
- (NSMutableArray*) fetchWorkitemsFromUrl:(NSString*) path {
	if(![self loadConfiguration]) {
		[[QuestetraBPMAppDelegate sharedApp] handleAuthenticationError];
		return nil;
	};
	NSString *urlString = [contextRoot stringByAppendingString:path];
	NSURL *url = [NSURL URLWithString:urlString];
	NSString *jsonString = [[NSString alloc] initWithData:[self loadDataFromURLForcingBasicAuth:url] encoding:NSUTF8StringEncoding];
	// NSLog(@"QBPMClient.fetchWorkitems result: %@", jsonString);	
	if([jsonString length] == 0) {
		[[QuestetraBPMAppDelegate sharedApp] handleAuthenticationError];
        return nil;
    }
	return [self parseJson:jsonString];
}

- (BOOL) acceptWorkitem:(long) workitemId {
	NSString *urlString = [NSString stringWithFormat:@"%@API/PE/Workitem/batchAccept?workitemIds=%d",
                           contextRoot, workitemId];
	NSURL *url = [NSURL URLWithString:urlString];
	NSString *jsonString = [[NSString alloc] initWithData:[self loadDataFromURLForcingBasicAuth:url] encoding:NSUTF8StringEncoding];
    if([jsonString length] == 0) {
        return NO;
    }    
    NSDictionary *jsonDictionary = [jsonString JSONValue];
	NSArray *jsonArray = [jsonDictionary objectForKey:@"results"];
	for(NSDictionary *o in jsonArray) {
		AcceptResult *result = [[AcceptResult alloc] initWithJsonDic: o];
        if(result.workitemId == workitemId && result.success) {
            return YES;
        }
	}
    return NO;
}

- (NSMutableArray*) parseJson:(NSString*) jsonString{
	NSDictionary *jsonDictionary = [jsonString JSONValue];
	NSArray *jsonArray = [jsonDictionary objectForKey:@"workitems"];
	NSArray *jsonArraySorted = [jsonArray sortedArrayUsingDescriptors:[NSArray arrayWithObject: [NSSortDescriptor sortDescriptorWithKey:@"offerDatetime" ascending:NO]]];
	NSMutableArray *workitems = [[NSMutableArray alloc] init];
	for(NSDictionary *o in jsonArraySorted) {
		WorkitemEntry *workitem = [[WorkitemEntry alloc] initWithJsonDic: o];
		[workitems addObject: workitem];
		[workitem retain];
	}
	[workitems retain];
	return workitems;
}

- (NSData *) loadDataFromURLForcingBasicAuth:(NSURL *) url {
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	[self addAuthorizationHeader:request];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSData* response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    return response;
}

- (void) addAuthorizationHeader:(NSMutableURLRequest*) request {
	NSString *authString = [Base64 encode:[[NSString stringWithFormat:@"%@:%@",email, password] dataUsingEncoding:NSUTF8StringEncoding]]; 
    // NSLog(@"Authorization :%@", authString);
	[request setValue:[NSString stringWithFormat:@"Basic %@", authString] forHTTPHeaderField:@"Authorization"];	
	[request setHTTPShouldHandleCookies:NO];
}

@end
